package com.wufun.overseas.tools;

import com.wufun.baselibrary.download.CommonDownloadFactory;
import com.wufun.baselibrary.download.CommonDownloadTask;
import com.wufun.baselibrary.utils.FileUtils;
import com.wufun.overseas.common.TabTypeInterface;
import com.wufun.overseas.main.base.MyApplication;
import com.wufun.overseas.models.db.DownLoadModel;
import com.wufun.overseas.models.greendao.gen.DownLoadModelDao;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by tangbl on 2017/12/2 0002.
 */

public class DownloadManager {

    private static DownloadManager downloadManager;

    private DownloadManager(){
        mDownLoadModelDao = MyApplication.getMyApplication().getmDownLoadModelDao();
    }

    public static DownloadManager getInstance(){
        if(downloadManager==null) downloadManager = new DownloadManager();
        return downloadManager;
    }

    private DownLoadModelDao mDownLoadModelDao;

    /**
     * 获取所有下载任务
     * */
    public List<DownLoadModel> getAllDownload() {
        return mDownLoadModelDao.queryBuilder().orderDesc(DownLoadModelDao.Properties.OpenRecentTime).list();
    }

    /**
     * 获取所有下载已完成的任务
     * */
    public List<DownLoadModel> getAllFinishDownload() {
        return mDownLoadModelDao.queryBuilder()
                .where(DownLoadModelDao.Properties.Status.eq(CommonDownloadTask.STATUS_FINISH))
                .orderDesc(DownLoadModelDao.Properties.OpenRecentTime).list();
    }

    /**
     * 检查是否有未完成任务
     * */
    public boolean getAllNotFinishDownload() {
        List<DownLoadModel> temp = mDownLoadModelDao.queryBuilder()
                .where(DownLoadModelDao.Properties.Status.notEq(CommonDownloadTask.STATUS_FINISH)).list();
        if (temp!=null && temp.size()>0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取所有下载已完成的任务
     * */
    public DownLoadModel getDownloadByUrl(String url) {
        return mDownLoadModelDao.queryBuilder()
                .where(DownLoadModelDao.Properties.DownloadUrl.eq(url)).unique();
    }

    /**
     * 获取制定类别的下载任务
     * */
    public List<DownLoadModel> getDownloadByType(int type) {
        if (type == TabTypeInterface.TYPE_ALL) {
            return getAllFinishDownload();
        } else if (type == TabTypeInterface.TYPE_LOCAL) {
            return mDownLoadModelDao.queryBuilder().where(DownLoadModelDao.Properties.Type.eq(type)
                    , DownLoadModelDao.Properties.Status.eq(CommonDownloadTask.STATUS_FINISH))
                    .orderDesc(DownLoadModelDao.Properties.OpenRecentTime).list();
        } else {
            List<DownLoadModel> resultList = new ArrayList<>();
            List<DownLoadModel> temptList = getAllFinishDownload();
            if (temptList==null || temptList.size()==0)
                return resultList;

            for (int i=0;i<temptList.size();i++) {
                String str = temptList.get(i).getTypeStr();
                if (!str.isEmpty()) {
                    String[] strList = str.split(",");
                    for (int j=0;j<strList.length;j++) {
                        if (type == TabTypeInterface.TYPE_ACTION) {
                            if ((type+"").equals(strList[j])
                                    || (TabTypeInterface.TYPE_ACTION2+"").equals(strList[j]) ) {
                                resultList.add(temptList.get(i));
                            }
                        } else {
                            if ((type+"").equals(strList[j])) {
                                resultList.add(temptList.get(i));
                            }
                        }
                    }
                }
            }
            return resultList;
        }
    }

    /**
     * 关键字搜索已完成
     * */
    public List<DownLoadModel> searchDownloadByKey(String str) {
        return mDownLoadModelDao.queryBuilder().where(DownLoadModelDao.Properties.GameName.like("%"+str+"%")
                , DownLoadModelDao.Properties.Status.eq(CommonDownloadTask.STATUS_FINISH))
                .orderDesc(DownLoadModelDao.Properties.OpenRecentTime).list();
    }

    /**
     * 获取未完成任务
     * */
    public List<DownLoadModel> getnotFinishDownload() {
        return mDownLoadModelDao.queryBuilder().where(DownLoadModelDao.Properties.Status.notEq(CommonDownloadTask.STATUS_FINISH))
                .orderDesc(DownLoadModelDao.Properties.OpenRecentTime).list();
    }

    /**
     * 插入
     * */
    public void insertDownload(DownLoadModel downLoadModel) {
        if (downLoadModel == null) return;
        if (isExist(downLoadModel.getDownloadUrl())) {
            updataDownload(downLoadModel);
        } else {
            mDownLoadModelDao.insertOrReplace(downLoadModel);
        }
    }

    /**
     * 更新
     * */
    public void updataDownload(DownLoadModel downLoadModel) {
        if (downLoadModel == null) return;
        mDownLoadModelDao.update(downLoadModel);
    }

    /**
     * 更新
     * */
    public void updataDownload(List<DownLoadModel> downLoadModel) {
        if (downLoadModel == null) return;
        mDownLoadModelDao.updateInTx(downLoadModel);
    }

    /**
     * 更新状态
     * */
    public void updataDownload(String downUrl, int status, String speed) {
        synchronized (mDownLoadModelDao) {
            DownLoadModel temp = mDownLoadModelDao.queryBuilder().where(DownLoadModelDao.Properties.DownloadUrl.eq(downUrl)).unique();
            if (temp == null) return;
            temp.setStatus(status);
            temp.setSpeed(speed);
            mDownLoadModelDao.updateInTx(temp);
        }
    }

    /**
     * 更新进度
     * */
    public void updataProDownload(String downUrl, int pro) {
        synchronized (mDownLoadModelDao) {
            DownLoadModel temp = mDownLoadModelDao.queryBuilder().where(DownLoadModelDao.Properties.DownloadUrl.eq(downUrl)).unique();
            if (temp == null) return;
            temp.setProgress(pro);
            mDownLoadModelDao.updateInTx(temp);
        }
    }

    /**
     * 更新状态
     * */
    public void updataDownload(String downUrl, int status) {
        synchronized (mDownLoadModelDao) {
            DownLoadModel temp = mDownLoadModelDao.queryBuilder().where(DownLoadModelDao.Properties.DownloadUrl.eq(downUrl)).unique();
            if (temp == null) return;
            temp.setStatus(status);
            mDownLoadModelDao.updateInTx(temp);
        }
    }

    /**
     * 更新时间
     * */
    public void updataDownload(String downUrl, long time) {
        synchronized (mDownLoadModelDao) {
            DownLoadModel temp = mDownLoadModelDao.queryBuilder().where(DownLoadModelDao.Properties.DownloadUrl.eq(downUrl)).unique();
            if (temp == null) return;
            temp.setOpenRecentTime(time);
            mDownLoadModelDao.updateInTx(temp);
        }
    }

    /**
     * 更新totalSize
     * */
    public void updataDownloadTotalSize(String downUrl, long size) {
        synchronized (mDownLoadModelDao) {
            DownLoadModel temp = mDownLoadModelDao.queryBuilder().where(DownLoadModelDao.Properties.DownloadUrl.eq(downUrl)).unique();
            if (temp == null) return;
            temp.setTotalSize(size);
            mDownLoadModelDao.updateInTx(temp);
        }
    }

    /**
     * 删除
     * */
    public void deleteDownload(String downUrl) {
        DownLoadModel temp = mDownLoadModelDao.queryBuilder().where(DownLoadModelDao.Properties.DownloadUrl.eq(downUrl)).unique();
        if (temp!=null) {
            if (temp.getStatus() != CommonDownloadTask.STATUS_FINISH)
                CommonDownloadFactory.get().cancelTask(temp.getDownloadUrl());
            File file = new File(temp.getDownloadDir()+temp.getGameZipName());
            if (file.exists())
                FileUtils.deleteFile(file);
            File file2 = new File(temp.getGamePath());
            if (file2.exists())
                FileUtils.deleteFile(file2);
            mDownLoadModelDao.delete(temp);
        }
    }

    /**
     * 删除所有
     * */
    public void deleteAllDownload() {
        File file = new File(MyApplication.getMyApplication().getAppRootPath());
        FileUtils.deleteFile(file);
        mDownLoadModelDao.deleteAll();
    }

    /**
     * 删除所有已完成下载
     * */
    public void deleteAllFinishDownload() {
        List<DownLoadModel> list = getAllFinishDownload();
        if (list!=null) {
            for (int i=0;i<list.size();i++) {
                DownLoadModel temp = list.get(i);
                if (temp.getStatus() != CommonDownloadTask.STATUS_FINISH)
                    CommonDownloadFactory.get().cancelTask(temp.getDownloadUrl());
                File file = new File(temp.getDownloadDir()+temp.getGameZipName());
                if (file.exists())
                    FileUtils.deleteFile(file);
                File file2 = new File(temp.getGamePath());
                if (file2.exists())
                    FileUtils.deleteFile(file2);
                mDownLoadModelDao.delete(temp);
            }
        }
    }

    /**
     * 下载任务是否存在
     * */
    public boolean isExist(String downUrl) {
        DownLoadModel temp = mDownLoadModelDao.queryBuilder().where(DownLoadModelDao.Properties.DownloadUrl.eq(downUrl)).unique();
        if (temp==null)
            return false;
        else
            return true;
    }

    /**
     * 下载任务是否完成
     * */
    public boolean isFinish(String downUrl) {
        DownLoadModel temp = mDownLoadModelDao.queryBuilder().where(DownLoadModelDao.Properties.DownloadUrl.eq(downUrl)
                , DownLoadModelDao.Properties.Status.eq(CommonDownloadTask.STATUS_FINISH)).unique();
        if (temp==null)
            return false;
        else
            return true;
    }

    public int getDownloadTaskStatus(String downUrl) {
        DownLoadModel temp = mDownLoadModelDao.queryBuilder().where(DownLoadModelDao.Properties.DownloadUrl.eq(downUrl)).unique();
        if (temp==null)
            return -2;
        else
            return temp.getStatus();
    }
}
